/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.cef.repository.dac;


import com.inspur.edp.cef.api.RefObject;
import com.inspur.edp.cef.api.repository.DbParameter;
import com.inspur.edp.cef.api.repository.GspDbDataType;
import com.inspur.edp.cef.api.repository.GspDbType;
import com.inspur.edp.cef.api.repository.adaptor.IRepositoryAdaptor;
import com.inspur.edp.cef.api.repository.readerWriter.ICefReader;
import com.inspur.edp.cef.entity.condition.EntityFilter;
import com.inspur.edp.cef.entity.condition.NodeSortInfo;
import com.inspur.edp.cef.entity.condition.RetrieveFilter;
import com.inspur.edp.cef.entity.dependenceTemp.DataValidator;
import com.inspur.edp.cef.entity.entity.IChildEntityData;
import com.inspur.edp.cef.entity.entity.IEntityData;

import com.inspur.edp.cef.repository.adaptor.AdaptorRetrieveParam;
import javax.swing.text.html.parser.Entity;
import java.util.*;
import java.sql.SQLException;

public abstract class MainEntityDac extends EntityDac
{


		///#region retrieve
	public final java.util.List<IEntityData> retrieveByIds(java.util.List<String> dataIds)  {
		return retrieveByIds(dataIds,null);
	}

    public final java.util.List<IEntityData> retrieveByIds(java.util.List<String> dataIds,RetrieveFilter retrieveFilter)  {
        if (dataIds == null || dataIds.size() < 1)
        {
            throw new IllegalArgumentException("传入的数据ID列表为空。");
        }
        if (!getUseDataCache())
        {
            return retrieveByIdsFromAdapter(dataIds,retrieveFilter);
        }

        java.util.ArrayList<String> missingDataIds = null;
        RefObject<ArrayList<String>> tempRef_missingDataIds = new RefObject<java.util.ArrayList<String>>(missingDataIds);
        java.util.List<IEntityData> datas =new ArrayList<>();
        missingDataIds=(ArrayList<String>)dataIds;
        //Java版临时注释
//		EntityDataCacheService.getInstance().getDatas(getCacheConfigID(), dataIds, tempRef_missingDataIds)
//		missingDataIds = tempRef_missingDataIds.argvalue;
        if (missingDataIds == null || missingDataIds.isEmpty())
        {
            return datas;
        }

        java.util.List<IEntityData> missingDatas = retrieveByIdsFromAdapter(dataIds,retrieveFilter);
        if (missingDatas == null || missingDatas.isEmpty())
        {
            return datas;
        }

        if (datas == null)
        {
            datas = new java.util.ArrayList<IEntityData>();
        }

        for (IEntityData item : missingDatas)
        {
            datas.add(item);
        }
        //Java版临时注释
//		EntityDataCacheService.getInstance().AddDatasToCache(getCacheConfigID(), missingDatas);
        return datas;
    }



	@Override
	public boolean isDatasEffectiveByCache(java.util.ArrayList<String> dataIds, RefObject<java.util.ArrayList<String>> missingDataIds)  {
		java.util.List<IEntityData> datas = retrieveByIds(dataIds);
		missingDataIds.argvalue = new java.util.ArrayList<String>();
		java.util.ArrayList<String> tempDataIds = new java.util.ArrayList<String>();

		for (IEntityData item : datas)
		{
			if (item != null)
			{
				tempDataIds.add(item.getID());
			}
		}


		for (String item : dataIds)
		{
			if (tempDataIds.contains(item) == false)
			{
				missingDataIds.argvalue.add(item);
			}
		}
		return missingDataIds.argvalue.isEmpty();
	}

	private java.util.List<IEntityData> retrieveByIdsFromAdapter(java.util.List<String> dataIds,RetrieveFilter retrieveFilter)  {

        EntityFilter filter=null;
        if(retrieveFilter!=null&&retrieveFilter.getNodeFilters()!=null) {
					if(this instanceof MainEntityDac && retrieveFilter.getNodeFilters().containsKey("RootNode"))
						filter = retrieveFilter.getNodeFilters().get("RootNode");
					else if(retrieveFilter.getNodeFilters().containsKey(this.getNodeCode()))
						filter = retrieveFilter.getNodeFilters().get(getNodeCode());
				}
		List<IEntityData> retrieveRezs = getEntityAdaptor().getDataByIds(dataIds,filter);
		if (retrieveRezs == null || retrieveRezs.size() < 1)
		{
			return null;
		}
		ArrayList<NodeSortInfo> nodeSortConditions=new ArrayList<>();
		getNodeSortConditions(retrieveFilter,nodeSortConditions);
		retrieveChildren(retrieveRezs, dataIds,nodeSortConditions,new AdaptorRetrieveParam(getNodeCode(), retrieveFilter));

		return retrieveRezs;
	}

	private void getNodeSortConditions(RetrieveFilter retrieveFilter, ArrayList<NodeSortInfo> nodeSortConditions){
		if (retrieveFilter==null||retrieveFilter.getNodeFilters()==null||retrieveFilter.getNodeFilters().size()<=0){
			nodeSortConditions=null;
			return;
		}
		Iterator iter= retrieveFilter.getNodeFilters().entrySet().iterator();
		while(iter.hasNext()){
			NodeSortInfo info=new NodeSortInfo();
			String key=((HashMap.Entry) iter.next()).getKey().toString();
			info.setNodeCode(key);
			info.setSortConditions(retrieveFilter.getNodeFilters().get(key).getSortConditions());

			nodeSortConditions.add(info);
		}
	}


	public final IEntityData retrieveById(String dataId, java.util.ArrayList<NodeSortInfo> nodeSortConditions) throws SQLException {
		DataValidator.checkForEmptyString(dataId, "dataId");
		if (getUseDataCache() == false)
		{
			return retrieveByIdFromAdapter(dataId, nodeSortConditions,null);
		}
		IEntityData data=null;
		//Java版临时注释
//		IEntityData data = EntityDataCacheService.getInstance().GetData(getCacheConfigID(), dataId);
		if (data == null)
		{
			data = retrieveByIdFromAdapter(dataId, nodeSortConditions,null);
			if (data != null)
			{
				//Java版临时注释
//				EntityDataCacheService.getInstance().AddDataToCache(getCacheConfigID(), data);
			}
		}
		return data;
	}

	public final  IEntityData retrieveById(String dataId, ArrayList<NodeSortInfo> nodeSortInfos, RetrieveFilter retrieveFilter) {
		DataValidator.checkForEmptyString(dataId, "dataId");
		if (getUseDataCache() == false) {
			return retrieveByIdFromAdapter(dataId, nodeSortInfos, retrieveFilter);
		}
		IEntityData data = null;
		//Java版临时注释
//		IEntityData data = EntityDataCacheService.getInstance().GetData(getCacheConfigID(), dataId);
		if (data == null) {
			data = retrieveByIdFromAdapter(dataId, nodeSortInfos, retrieveFilter);

			if (data != null) {
				//Java版临时注释
//				EntityDataCacheService.getInstance().AddDataToCache(getCacheConfigID(), data);
			}
		}
		return data;
	}

	private IEntityData retrieveByIdFromAdapter(String dataId, java.util.ArrayList<NodeSortInfo> nodeSortConditions,RetrieveFilter retrieveFilter)
	{
		AdaptorRetrieveParam param = new AdaptorRetrieveParam(getNodeCode(), retrieveFilter);
		//retrieveRez主表数据
		IEntityData retrieveRez = getEntityAdaptor().getDataByIDWithPara(dataId,param);
		if (retrieveRez == null)
		{
			return null;
		}
		if (nodeSortConditions != null)
		{
			retrieveChildren(java.util.Arrays.asList(retrieveRez), java.util.Arrays.asList(dataId),
					nodeSortConditions,param);
			return retrieveRez;
		}
		retrieveChildren(java.util.Arrays.asList(retrieveRez), java.util.Arrays.asList(dataId),
				null,param);
		return retrieveRez;
	}

    protected final void retrieveChildren(java.util.List<IEntityData> retrieveResults, java.util.List<String> dataIds,
                                          java.util.ArrayList<NodeSortInfo> nodeSortConditions)
    {
        retrieveChildren(retrieveResults,dataIds,nodeSortConditions,new AdaptorRetrieveParam());
    }

	private final void retrieveChildren(java.util.List<IEntityData> retrieveResults, java.util.List<String> dataIds,
                                          java.util.ArrayList<NodeSortInfo> nodeSortConditions,AdaptorRetrieveParam adaptorRetrieveParam)  {
		java.util.List<ChildEntityDac> childDacList = innerGetChildDacList();
		if (childDacList == null || childDacList.size() < 1)
		{
			return;
		}
		RetrieveFilter retrieveFilter = adaptorRetrieveParam.getRetrieveFilter();
		for (ChildEntityDac childDac : childDacList)
		{
			if(retrieveFilter!=null&&retrieveFilter.isOnlyRetrieveSomeChilds()&&retrieveFilter.getRetrieveChildNodeList().contains(childDac.getNodeCode())==false)
				continue;
			java.util.Map<String, java.util.List<IChildEntityData>> childData;
			if (dataIds.size() == 1)
            {
                List<DbParameter> parameters=new ArrayList<>();
                parameters.add( getEntityAdaptor().buildParam("ID", getEntityAdaptor().getContainColumns().getPrimaryKey().getColumnType(), dataIds.get(0).length(), dataIds.get(0)));
                childData = childDac.getDataByParentsWithPara("", getEntityAdaptor().getIDFilter(), nodeSortConditions, new java.util.ArrayList<String>()
                        ,parameters,adaptorRetrieveParam);
            }
			else
            {
                childData = childDac.getDataByParentsWithPara("", getEntityAdaptor().getBatchInIDsFilter(dataIds), nodeSortConditions, new java.util.ArrayList<String>(),null,adaptorRetrieveParam);
            }

			if (childData == null || childData.isEmpty()) {
				continue;
			}
			//给子表赋值
			mergeChildDatas(childDac.getNodeCode(), retrieveResults, childData);
		}
	}

		///#endregion

	//region VersionControl
	public Date getVersionControlValue(String dataId)
	{
		DataValidator.checkForEmptyString(dataId, "dataId");
		return getEntityAdaptor().getVersionControlValue(dataId);
	}

	public HashMap<String, Date> getVersionControlValues(List<String> dataIds)
	{
		if (dataIds == null || dataIds.size() < 1)
			throw new RuntimeException("没有传入正确的数据ID:"+"dataIds");
		return getEntityAdaptor().getVersionControlValues(dataIds);
	}
	//endregion
}
